<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽效果</title>
    <style>
        div {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: tomato;
        }
    </style>

    <!-- 
        拖拽效果
          思路: 
             1. 拖拽的区块移到 鼠标的指定位置
                1.1 鼠标移动到的位置
                1.2 将位置赋值给拖拽区块
            2. 定义一个鼠标左键按钮开关，
                如果左键按钮开关为true，当鼠标移动时拖拽区块跟随移动
                否则，鼠标移动时拖拽区块不跟随移动
            3. 计算鼠标左键按下位置
                   //鼠标距离区块左边距离
                    l = e.offsetX
                    //鼠标距离区块顶部距离
                    t = e.offsetY
     -->
</head>

<body>
    <div></div>

    <script>
        var box = document.querySelector('div')
        var ismove = false //是左键是否按下开关
        var l = 0
        var t = 0
        //事件源是整个docment文件,
        document.onmousemove = function (e) {
            if (!ismove) {
                return
            }
            e = e || window.event
            var x = e.pageX - l
            var y = e.pageY - t
            console.log('x ', x, 'y ', y)
            box.style.top = y + 'px'
            box.style.left = x + 'px'
        }

        //拖拽区块鼠标左键按下事件
        box.onmousedown = function (e) {
            e = e || window.event
            ismove = true

            //鼠标距离区块左边距离
            l = e.offsetX
            //鼠标距离区块顶部距离
            t = e.offsetY

            console.log('左键按下事件 ', ismove)
        }

        box.onmouseup = function () {
            ismove = false
            console.log('左键抬起事件 ', ismove)
        }

        box.oncontextmenu = function(){
            alert('鼠标右键事件')
        }
    </script>
</body>

</html>